package com.kukudb.asaproject.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Base64;

public class ImageUtil {
    public static String convertImageToBase64Str(String imageFileName) throws IOException {
        ByteArrayOutputStream baos = null;
        try {
            String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            File imageFile = new File(imageFileName);
            BufferedImage bufferedImage = ImageIO.read(imageFile);
            baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, suffix, baos);
            byte[] bytes = baos.toByteArray();
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (baos != null) {
                baos.close();
            }
        }
        return null;
    }
    public static void convertBase64StrToImage(String base64String, String imageFileName) throws IOException {
        ByteArrayInputStream bais = null;
        try {
            String suffix = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            byte[] bytes = Base64.getDecoder().decode(base64String);
            bais = new ByteArrayInputStream(bytes);
            BufferedImage bufferedImage = ImageIO.read(bais);
            File imageFile = new File(imageFileName);
            ImageIO.write(bufferedImage, suffix, imageFile);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bais != null) {
                bais.close();
            }
        }
    }
}
